//
//  EeSearchController.swift
//  TRHouse
//
//  Created by zhu xietong on 2018/5/16.
//  Copyright © 2018年 tianrun. All rights reserved.
//

import Foundation
import Eelay
 
public protocol SearchRealizition {
    func updateSearchKey(key:String)
}

open class EeSearchController: ASCollectionContainer{
    override open var initTopStyle: EeTopStyle{
        get{
//            return .dark(with: UIColor(shex: "#F1F1F1"))
            return .default
//            self.top_style = EeTopStyle.dark(with: UIColor(shex: "#F1F1F1"))

        }
    }
    
    public let navBar = EeSearchNav()
    
    public let contentView = UIView()
    
    override open var LoadingPresenterBg: UIView{
        return contentView
    }
    
    open var searchKey:String = ""
        {
        didSet{
            self.navBar.searchBar.textField.text = searchKey
            change(searchKey: searchKey)
        }
    }
    
    open func change(searchKey:String){
        updateListWith()
    }
    
    open func change(filterValues:NSMutableDictionary){
        updateListWith()
    }
    
    public var needSearchFocus = false
    
    public var filterValues = [String:Any]()
    {
        didSet{
            change(filterValues: filterValues.mutable_dictionary)
        }
    }
    
    public var loadIndex = 0
    
    open func setNavTitleView(){
        weak var wself = self
        self.navigationItem.titleView = navBar
        navBar.controller = self
        navBar.titleL.font = UIFont.systemFont(ofSize: 18)
        navBar.navTransparent = .yes
        //        header.scrollViewDidScroll(scrollView: tableView)
        navBar.searchBar.observerAction = {
            status in
            switch status {
            case .begin:
                wself?.menu.control.close()
            case .searchDone(let str):
                wself?.searchKey = str
            default:
                break
            }
        }
    }
    
    
    override open func viewDidLoad() {
        //        self.page_load_section = "section0"
        //        self.content = TermsContainer.table(
        //            title: "我的关注",
        //            emptyMsg:"没有相关内容",
        //            net: JoTask().post.log.log_response().url(_URL.json).apijson(json),
        //            params:nil,//除了分页参数之外的额外参数
        //            node: "Building[]",
        //            cellType: Cell.self,
        //            cellHeigth: nil,
        //            detailType: BuildingDetailCtr.self,
        //            test: false
        //        )
        
        super.viewDidLoad()
        paginator.refreshHeader = UIRefreshHead()
        collectionNode.view.backgroundColor = .clear
        setNavTitleView()
    }
    
    public let menu = EeFilterMenu()
    
    override open func layCollection(collectionView: UIView) {
        
        let item1 = FilterOption()
        item1.align = .left
        item1.filterKey = "type_price"
        item1.button.ui.ntitle(title: "楼盘筛选").nimage(UIImage(named: "lplb_xiala")).ncolor(hex: "#070707").scolor(hex: UIColor.main_hex).font(size: 10).imagePosition(.right)
        item1.filterSelector = .dropView(BuildingTypeSelector())
        
        
        let item2 = FilterOrder()
        item2.button.ui.ncolor(hex: "#070707").ntitle(title: "开盘时间").nimage(UIImage(named: "lplb_xiala")).scolor(hex: UIColor.main_hex).font(size: 10).imagePosition(.right)
        item2.asc = ("开盘时间","time_deliver","",nil)
        item2.desc = ("开盘时间","time_deliver","-",nil)
        
        let item3 = FilterOrder()
        item1.align = .right

        item3.button.ui.ncolor(hex: "#070707").ntitle(title: "均价排序").nimage(UIImage(named: "lplb_xiala")).scolor(hex: UIColor.main_hex).font(size: 10).imagePosition(.right)
        item3.asc = ("均价排序","price_low","",nil)
        item3.desc = ("均价排序","price_low","-",nil)
        view.backgroundColor = .white
        
        
        menu.cellType = MenuCell.self
        view.eelay = [
            [menu,[ee.T.L.R,[(TP.topHeight),0,0]],"40"],
            [jo_contentView,[ee.T,(TP.topHeight+40)],[ee.L.B.R]],
        ]
        
        jo_contentView.eelay = [
            [collectionView,[ee.T],[ee.L.B.R]],
        ]
        
        menu.flow.sectionInset = [0,.hpadding]
        
        item1.itemWidth = Swidth/3.0
        item2.itemWidth = Swidth/3.0
        item3.itemWidth = Swidth/3.0
        
        menu.collectionViewConfig = {
            cv in
            if let flow = cv.collectionViewLayout as? UICollectionViewFlowLayout
            {
                flow.minimumInteritemSpacing = 0
                flow.minimumLineSpacing = 0
            }
        }
        menu.items = [item1,item2,item3]
        menu.observerFilter = {[weak self] info in
            
            self?.filterValues = info
        }
        menu.controller = self
        menu.backgroundColor = UIColor(shex: "#fff")
    }
    
    
    open func updateListWith()  {
        
        let values = filterValues.mutable_dictionary
        
        let fmin = values[float:"type_price.price.min",0.0]
        let fmax = values[float:"type_price.price.max",0.0]
        
        //        print("++++||\(values)")
        let __type = values["type_price.buildingType.type",""]
        let __max = max(fmax, fmin)
        let __min = min(fmax, fmin)
        
        var condition:[String:Any] = [String:Any]()
        if __type.len > 0 {
            condition["type"] = __type
        }
        if __max > 0{
            condition["price_low{}"] = ">=\(__min.print(num: 0))"
            //            condition["price_high{}"] = "<=\(__max.print(num: 0))"
        }
        
        if let order = DataNode<NSMutableDictionary>.path(node: "order", values){
            let key = order["key",""]
            let value = order["value",""]
            condition["@order"] = "\(key)\(value)"
        }
        if searchKey.len > 0{
            condition["name$"] = "%\(searchKey)%"
        }
        
        paginator.net.apijson([
            "Building[]":[
                "Building":condition
            ]
            ])
        reload_page()
        
    }
    
    open override func touch(cell: Any, actionID: String, model: NSMutableDictionary) {
        
    }
    
    override open func viewDidDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navBar.searchBar.status = .lostFocus
        
    }
    
    override open func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if loadIndex == 0
        {
            if !needSearchFocus{
                firstAppearLoad()
            }
        }
        loadIndex = loadIndex + 1
    }
    
    open func firstAppearLoad(){
        reload_page()
    }
    
    override open func viewDidAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if needSearchFocus{
            
            navBar.searchBar.status = .begin
            needSearchFocus = false
        }
        
        
    }
    
    deinit {
    }
    
}

extension EeSearchController{
    
    open class FixedMenuCell: EeFilterItemCell {
        
        let indicator = UIView()
        let indicatorH:CGFloat = TP.separatorHeight
        override open func addLayoutRules() {
            let bk = UIView()
            let spec = UIView()
            contentView.eelay = [
                [bk,[ee.T.L.B.R,[0,0,-indicatorH,0]]],
                [indicator,[ee.L.B.R],"\(indicatorH)"],
                //                [spec,[ee.T.B.R,[0,0,0]],TP.separatorHeight],
            ]
            contentView.clipsToBounds = false
            self.clipsToBounds = false
            
            spec.backgroundColor = UIColor(shex:"#e0e0e0")
            indicator.backgroundColor = UIColor.table_bg_color
            contentView.backgroundColor = UIColor.white
        }
        
        override open func loadItem(item: FilterItemSupport) {
            print("02===0ss0s00sooo",item.align.rawValue)
            switch item.align {
             case .left:
                 contentView.eelay = [
                     [button,[ee.T.L.B]]
                 ]
                break
             case .right:
                contentView.eelay = [
                     [button,[ee.T.R.B]]
                 ]
                break
             default:
                contentView.eelay = [
                     [button,[ee.T.L.B.R]]
                 ]
                break
             }
            
            if item.type == .order{
                return
            }
            //            weak var wself = self
            var aitem = item
            aitem.buttonAction = {
                bt in
                if bt.isSelected{
                    //                    wself?.indicator.backgroundColor = UIColor(shex: __main_hex)
                    //                wself?.contentView.backgroundColor = .red
                }else{
                    //                    wself?.indicator.backgroundColor = .clear
                    //                wself?.contentView.backgroundColor = .blue
                }
            }
        }
    }

    open class MenuCell: EeFilterItemCell {
        
        let indicator = UIView()
        let indicatorH:CGFloat = TP.separatorHeight
        override open func addLayoutRules() {
            let bk = UIView()
            let spec = UIView()
            contentView.eelay = [
                [bk,[ee.T.L.B.R,[0,0,-indicatorH,0]]],
                [indicator,[ee.L.B.R],"\(indicatorH)"],
                //                [spec,[ee.T.B.R,[0,0,0]],TP.separatorHeight],
            ]
            contentView.clipsToBounds = false
            self.clipsToBounds = false
            
            spec.backgroundColor = UIColor(shex:"#e0e0e0")
            indicator.backgroundColor = UIColor._tableBackground
            contentView.backgroundColor = UIColor.white
        }
        
        override open func loadItem(item: FilterItemSupport) {
            print("01===0ss0s00sooo",item.align.rawValue)
            switch item.align {
             case .left:
                 contentView.eelay = [
                     [button,[ee.T.L.B]]
                 ]
             case .right:
                contentView.eelay = [
                     [button,[ee.T.R.B]]
                 ]
             default:
                contentView.eelay = [
                     [button,[ee.T.L.B.R]]
                 ]
             }
            
            
//
//            let bt = item.button
//
//            contentView.addSubview(bt)
//            bt.translatesAutoresizingMaskIntoConstraints = false
//
//            let x = NSLayoutConstraint(item: bt, attribute: .centerX, relatedBy: .equal, toItem: contentView, attribute: .centerX, multiplier: 1, constant: 0)
//            let y = NSLayoutConstraint(item: bt, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: -indicatorH)
//            contentView.addConstraints([x,y])

            
            
            if item.type == .order{
                return
            }
            //            weak var wself = self
            var aitem = item
            aitem.buttonAction = {
                bt in
                if bt.isSelected{
                    //                    wself?.indicator.backgroundColor = UIColor(shex: __main_hex)
                    //                wself?.contentView.backgroundColor = .red
                }else{
                    //                    wself?.indicator.backgroundColor = .clear
                    //                wself?.contentView.backgroundColor = .blue
                }
            }
        }
    }
}

